<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/murmur/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/murmur/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/murmur/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/murmur/images/logo.svg" color="#222">

<link rel="stylesheet" href="/murmur/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.css">
  <script src="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.js"></script>

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/murmur/","scheme":"Gemini","version":"8.0.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"disqus","storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}};
  </script>

  <meta name="description" content="第5章：作用域闭包到底什么是闭包 本章讲解闭包(Closures)，它与作用域工作原理息息相关。 首先我用自己总结的三句话，简单说明什么是闭包： （1）首先我们要知道，变量的查找 规则 是由内到外的 ； （2）所以 子函数可以访问外部作用域  的变量； （3）如果 把子函数赋值给外部变量  时，此时外部变量就 拥有 了可以 访问封闭数据包的能力 ；   一个简单的闭包示例123456789func">
<meta property="og:type" content="article">
<meta property="og:title" content="《你不知道的JavaScript(上)》S01E05">
<meta property="og:url" content="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E05/index.html">
<meta property="og:site_name" content="汇话板">
<meta property="og:description" content="第5章：作用域闭包到底什么是闭包 本章讲解闭包(Closures)，它与作用域工作原理息息相关。 首先我用自己总结的三句话，简单说明什么是闭包： （1）首先我们要知道，变量的查找 规则 是由内到外的 ； （2）所以 子函数可以访问外部作用域  的变量； （3）如果 把子函数赋值给外部变量  时，此时外部变量就 拥有 了可以 访问封闭数据包的能力 ；   一个简单的闭包示例123456789func">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-12-01T14:10:10.000Z">
<meta property="article:modified_time" content="2020-12-01T15:07:26.963Z">
<meta property="article:author" content="William Leung">
<meta property="article:tag" content="你不知道的JavaScript">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E05/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>《你不知道的JavaScript(上)》S01E05 | 汇话板</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?a49081c570a782a242cdf6e19e1a584d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/murmur/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">汇话板</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">设定目标，放慢步调，用温和的力量自我改革</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/murmur/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/murmur/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <section class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%AC%AC5%E7%AB%A0%EF%BC%9A%E4%BD%9C%E7%94%A8%E5%9F%9F%E9%97%AD%E5%8C%85"><span class="nav-number">1.</span> <span class="nav-text">第5章：作用域闭包</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%B0%E5%BA%95%E4%BB%80%E4%B9%88%E6%98%AF%E9%97%AD%E5%8C%85"><span class="nav-number">1.0.1.</span> <span class="nav-text">到底什么是闭包</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%97%AD%E5%8C%85%E6%9A%B4%E9%9C%B2%E7%9A%84%E6%96%B9%E5%BC%8F%E4%B8%8D%E6%AD%A2%E4%B8%80%E7%A7%8D"><span class="nav-number">1.0.2.</span> <span class="nav-text">闭包暴露的方式不止一种</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%97%AD%E5%8C%85%E6%98%AF%E6%9C%80%E7%86%9F%E6%82%89%E7%9A%84%E9%99%8C%E7%94%9F%E4%BA%BA"><span class="nav-number">1.0.3.</span> <span class="nav-text">闭包是最熟悉的陌生人</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%97%AD%E5%8C%85%E8%A7%A3%E5%86%B3%E4%BA%86%E4%BB%80%E4%B9%88%E9%97%AE%E9%A2%98"><span class="nav-number">1.0.4.</span> <span class="nav-text">闭包解决了什么问题</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-%E7%94%A8%E9%97%AD%E5%8C%85%E9%80%A0%E5%9D%97%E7%BA%A7%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="nav-number">1.0.4.1.</span> <span class="nav-text">1. 用闭包造块级作用域</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-%E7%94%A8%E9%97%AD%E5%8C%85%E9%80%A0%E6%A8%A1%E5%9D%97"><span class="nav-number">1.0.4.2.</span> <span class="nav-text">2. 用闭包造模块</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%B0%8F%E7%BB%93"><span class="nav-number">1.0.5.</span> <span class="nav-text">小结</span></a></li></ol></li></ol></li></ol></div>
        </section>
        <!--/noindex-->

        <section class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">William Leung</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/murmur/archives">
          <span class="site-state-item-count">43</span>
          <span class="site-state-item-name">文章</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/murmur/categories/">
          
        <span class="site-state-item-count">9</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/murmur/tags/">
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </section>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">
      

      

  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E05/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/murmur/images/avatar.gif">
      <meta itemprop="name" content="William Leung">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="汇话板">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          《你不知道的JavaScript(上)》S01E05
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>
      

      <time title="创建时间：2020-12-01 22:10:10 / 修改时间：23:07:26" itemprop="dateCreated datePublished" datetime="2020-12-01T22:10:10+08:00">2020-12-01</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/murmur/categories/%E4%B8%80%E5%91%A8%E4%B8%80%E7%AB%A0%E5%89%8D%E7%AB%AF%E4%B9%A6/" itemprop="url" rel="index"><span itemprop="name">一周一章前端书</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>5.2k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>5 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="第5章：作用域闭包"><a href="#第5章：作用域闭包" class="headerlink" title="第5章：作用域闭包"></a>第5章：作用域闭包</h1><h3 id="到底什么是闭包"><a href="#到底什么是闭包" class="headerlink" title="到底什么是闭包"></a>到底什么是闭包</h3><ul>
<li>本章讲解<code>闭包(Closures)</code>，它与作用域工作原理息息相关。</li>
<li>首先我用自己总结的三句话，简单说明什么是闭包：<ul>
<li>（1）首先我们要知道，<strong>变量的查找</strong> 规则 <strong>是由内到外的</strong> ；</li>
<li>（2）所以 <strong>子函数可以访问外部作用域</strong>  的变量；</li>
<li>（3）如果 <strong>把子函数赋值给外部变量</strong>  时，此时外部变量就 <strong>拥有</strong> 了可以 <strong>访问封闭数据包的能力</strong> ；</li>
</ul>
</li>
<li>一个简单的闭包示例<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> a = <span class="number">2</span>;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">bar</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(a); <span class="comment">//2</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> bar;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> baz = foo();</span><br></pre></td></tr></table></figure></li>
<li>分析上述代码：<ul>
<li><code>bar</code>函数能访问外部<code>foo</code>函数的作用域，将<code>bar</code>传递给外部变量<code>baz</code>来执行；</li>
<li>此时<code>bar</code>函数在原来定义的词法作用域之外执行，同时持有<code>foo</code>函数作用域的引用，这就叫作闭包。</li>
</ul>
</li>
<li>并且通过闭包的执行方式，<code>foo</code>函数在执行后，其作用域不会被立即销毁（毕竟<code>bar</code>函数还要用的啊）</li>
</ul>
<h3 id="闭包暴露的方式不止一种"><a href="#闭包暴露的方式不止一种" class="headerlink" title="闭包暴露的方式不止一种"></a>闭包暴露的方式不止一种</h3><ul>
<li>闭包函数除了可以直接赋值给外部变量，也可以通过执行外部函数，将闭包函数以参数传递的方式暴露出去。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> <span class="function"><span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> a = <span class="number">2</span>;</span><br><span class="line">    <span class="comment">//闭包函数</span></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">baz</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(a);; <span class="comment">//2</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//执行外部函数，将闭包函数通过参数的方式传递进去</span></span><br><span class="line">    bar(baz)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> <span class="function"><span class="title">bar</span>(<span class="params">fn</span>)</span>&#123;</span><br><span class="line">    fn();</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

</li>
</ul>
<h3 id="闭包是最熟悉的陌生人"><a href="#闭包是最熟悉的陌生人" class="headerlink" title="闭包是最熟悉的陌生人"></a>闭包是最熟悉的陌生人</h3><ul>
<li>虽然闭包比较隐晦，但它绝不仅仅是一个好玩的玩具而已，在我们的代码中到处都有它的身影。</li>
<li>比如常见的定时函数<code>setTimeout()</code>：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">wait</span>(<span class="params">message</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="function"><span class="keyword">function</span> <span class="title">timer</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(message);</span><br><span class="line">    &#125;,<span class="number">1000</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
上述代码等价于：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//全局的setTimout函数准备就绪</span></span><br><span class="line"><span class="keyword">var</span> setTimout = <span class="function"><span class="keyword">function</span>(<span class="params">invokeFn</span>)</span>&#123;&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">wait</span>(<span class="params">message</span>)</span>&#123;</span><br><span class="line">    <span class="comment">//timer内部函数拥有对mesage的访问权</span></span><br><span class="line">    <span class="keyword">var</span> timer = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(message);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//执行setTimeout()函数，并将timer以参数方式传递进去</span></span><br><span class="line">    setTimout(timer);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li>是不是有似曾相似的感觉？内部函数<code>timer()</code>具有外部函数<code>wait()</code>作用域中的<code>message</code>变量的引用，它就是闭包。</li>
<li>除了定时函数之外，jQuery代码也普遍的在使用闭包，不信你看下面的代码：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//参数传递一个name字符串，选择器字符串</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">setupBot</span>(<span class="params">name,selector</span>)</span>&#123;</span><br><span class="line">    <span class="comment">//通过选择器字符串初始化成jQuery对象</span></span><br><span class="line">    <span class="comment">//绑定点击事件</span></span><br><span class="line">    $(selector).click(<span class="function"><span class="keyword">function</span> <span class="title">activator</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="comment">//打印外部函数的name</span></span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;Activating:&#x27;</span> + name);</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">setupBot(<span class="string">&#x27;Closure Bot 1&#x27;</span>,<span class="string">&#x27;#bot_1&#x27;</span>);</span><br><span class="line">setupBot(<span class="string">&#x27;Closure Bot 2&#x27;</span>,<span class="string">&#x27;#bot_2&#x27;</span>);</span><br></pre></td></tr></table></figure></li>
<li>其实无论何时何地，只要将函数当做参数进行传递，就有闭包的应用。</li>
<li>什么定时器、事件监听函数、Ajax请求回调函数、跨窗口通信、Web Workers等代码中，都普遍应用到了闭包。</li>
<li>它每天与我们擦肩而过，就好像那个最熟悉的陌生人。</li>
</ul>
<h3 id="闭包解决了什么问题"><a href="#闭包解决了什么问题" class="headerlink" title="闭包解决了什么问题"></a>闭包解决了什么问题</h3><h4 id="1-用闭包造块级作用域"><a href="#1-用闭包造块级作用域" class="headerlink" title="1. 用闭包造块级作用域"></a>1. 用闭包造块级作用域</h4><ul>
<li>我们先看问题： 我只是想依次输出循环的<code>i</code>（1 ~ 5）<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">1</span>;i&lt;=<span class="number">5</span>;i++)&#123;</span><br><span class="line">    setTimtou(<span class="function"><span class="keyword">function</span> <span class="title">timer</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(i);  </span><br><span class="line">    &#125;,<span class="number">0</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li>见鬼了，然而输出的结果却是五次6，这是为什么呢？</li>
<li>其根本原因是，定时器的回调函数永远在循环结束后才执行。</li>
<li>那你可能会想，哦，那我岂不是永远都不能在<code>for</code>循环中用定时器了？JavaScript真垃圾！诶诶，先别慌，我们来分析一下。</li>
<li>我们不是预期循环的每个迭代中，都有一个<code>i</code>的副本，然后输出它吗？通过闭包就能实现。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">1</span>;i&lt;=<span class="number">5</span>;i++)&#123;</span><br><span class="line">    (<span class="function"><span class="keyword">function</span>(<span class="params">index</span>)</span>&#123;</span><br><span class="line">        setTimtou(<span class="function"><span class="keyword">function</span> <span class="title">timer</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            <span class="built_in">console</span>.log(index);  </span><br><span class="line">        &#125;,<span class="number">0</span>)</span><br><span class="line">    &#125;)(i);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li>我们通过IIFE构造了一个块级作用域将<code>i</code>存了起来。</li>
<li>提到块级作用域，其实ES6的语法里还有一种更便捷的解决方式——<code>let</code>声明<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="keyword">let</span> i=<span class="number">1</span>;i&lt;=<span class="number">5</span>;i++)&#123;</span><br><span class="line">    setTimtou(<span class="function"><span class="keyword">function</span> <span class="title">timer</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(i);  </span><br><span class="line">    &#125;,<span class="number">0</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h4 id="2-用闭包造模块"><a href="#2-用闭包造模块" class="headerlink" title="2. 用闭包造模块"></a>2. 用闭包造模块</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">CoolModule</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> something = <span class="string">&#x27;cool&#x27;</span>;</span><br><span class="line">    <span class="keyword">var</span> another = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">doSomething</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(something);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">doAnother</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(another.join(<span class="string">&quot;,&quot;</span>));</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//对外暴露内部函数</span></span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">        doSomething : doSomething,</span><br><span class="line">        doAnother : doAnother</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>上述代码演示了JavaScript模块暴露。通过调用<code>CoolModule</code>函数创建一个模块实例，<code>CoolModule</code>返回的对象中包含内部函数的引用，就相当于模块的公共API。</li>
<li>当然上述代码可以任意调用多次，重复返回新的模块实例，我们可以改成单例模式：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//通过一个IIFE函数来包装</span></span><br><span class="line"><span class="keyword">var</span> foo = (<span class="function"><span class="keyword">function</span> <span class="title">CoolModule</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> something = <span class="string">&#x27;cool&#x27;</span>;</span><br><span class="line">    <span class="keyword">var</span> another = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">doSomething</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(something);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">doAnother</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(another.join(<span class="string">&quot;,&quot;</span>));</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//对外暴露内部函数</span></span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">        doSomething : doSomething,</span><br><span class="line">        doAnother : doAnother</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)();</span><br><span class="line"></span><br><span class="line">foo.doSomething();  <span class="comment">//cool</span></span><br><span class="line">foo.doAnother();    <span class="comment">//1,2,3</span></span><br></pre></td></tr></table></figure></li>
<li>模块的公共API不仅可以是内部私有变量的访问，也可以是修改私有变量的方法：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> foo = (<span class="function"><span class="keyword">function</span> <span class="title">CoolModule</span>(<span class="params">id</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> moduleId = id;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">showId</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(moduleId);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">uppcaseId</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        moduleId = moduleId.toUpperCase();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span>&#123;</span><br><span class="line">        showId : showId,</span><br><span class="line">        uppcaseId : uppcaseId</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)(<span class="string">&#x27;fooModule&#x27;</span>);</span><br><span class="line"></span><br><span class="line">foo.showId();</span><br><span class="line">foo.uppcaseId();</span><br><span class="line">foo.showId();</span><br></pre></td></tr></table></figure></li>
<li>其实大多数模块管理机制本质是也是通过类似的方式来实现的，我们来尝试写一个简版的模块管理器：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 定义牛批哄哄的超级模块管理器</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">var</span> SuperModules = (<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="comment">//所有的模块集合，以name作为key</span></span><br><span class="line">	<span class="keyword">var</span> moduleMap = &#123;&#125;;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">function</span> <span class="title">define</span>(<span class="params">name,deps,impl</span>)</span>&#123;</span><br><span class="line">		<span class="comment">//获取依赖</span></span><br><span class="line">		<span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">0</span>;i&lt;deps.length;i++)&#123;</span><br><span class="line">			deps[i] = moduleMap[deps[i]]		</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">//执行引入的模块，并以deps作为参数</span></span><br><span class="line">		moduleMap[name] = impl.apply(impl,deps);</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">function</span> <span class="title">get</span>(<span class="params">name</span>)</span>&#123;</span><br><span class="line">		reutrn moduleMap[name];</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//暴露公共API</span></span><br><span class="line">	<span class="keyword">return</span>&#123;</span><br><span class="line">		define : define,</span><br><span class="line">		get : get</span><br><span class="line">	&#125;</span><br><span class="line">&#125;)()</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 先定义一个bar模块</span></span><br><span class="line"><span class="comment"> * 没有依赖，impl是一个执行函数</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">SuperModules.define(<span class="string">&#x27;bar&#x27;</span>,[],<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">function</span> <span class="title">hello</span>(<span class="params">name</span>)</span>&#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="string">&#x27;let me introduce:&#x27;</span> + name;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> &#123;</span><br><span class="line">		hello : hello</span><br><span class="line">	&#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 再定义一个foo模块</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">SuperModules.difine(<span class="string">&#x27;foo&#x27;</span>,[<span class="string">&#x27;bar&#x27;</span>],<span class="function"><span class="keyword">function</span>(<span class="params">bar</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">var</span> hungry = <span class="string">&#x27;hippo&#x27;</span>;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">function</span> <span class="title">awesome</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">		<span class="built_in">console</span>.log(bar.hello(hungry).toUpperCase());</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">return</span> &#123;</span><br><span class="line">		awesome : awesome</span><br><span class="line">	&#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 调用测试</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">var</span> bar = SuperModules.get(<span class="string">&#x27;bar&#x27;</span>);</span><br><span class="line"><span class="keyword">var</span> foo = SuperModules.get(<span class="string">&#x27;foo&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//let me introduce: hippo</span></span><br><span class="line"><span class="built_in">console</span>.log(bar.hello(<span class="string">&#x27;hippo&#x27;</span>));</span><br><span class="line"><span class="comment">//let me introduce: HIPPO</span></span><br><span class="line">foo.awesome();</span><br></pre></td></tr></table></figure></li>
<li>是不是看起来比较复杂……不过不用担心，ES6以及添加了模块的语法支持！</li>
<li>ES6会将每个js文件当做独立的模块来处理，每个模块可以通过<code>import</code>关键字导入依赖的模块，或者通过<code>export</code>关键字导出API。你需要做的，只是拥抱ES6！</li>
<li><code>bar.js</code><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">hello</span>(<span class="params">name</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="string">&#x27;let me introduce:&#x27;</span> + name;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> hello;</span><br></pre></td></tr></table></figure></li>
<li><code>foo.js</code><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> hello <span class="keyword">from</span> <span class="string">&#x27;bar&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> hungry = <span class="string">&#x27;hippo&#x27;</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">awesome</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(bar.hello(hungry).toUpperCase());</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> awesome;</span><br></pre></td></tr></table></figure></li>
<li><code>baz.js</code><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span> foo <span class="keyword">from</span> <span class="string">&#x27;foo&#x27;</span>;</span><br><span class="line"><span class="built_in">module</span> bar <span class="keyword">from</span> <span class="string">&#x27;bar&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//let me introduce: hippo</span></span><br><span class="line"><span class="built_in">console</span>.log(bar.hello(<span class="string">&#x27;hippo&#x27;</span>));</span><br><span class="line"><span class="comment">//let me introduce: HIPPO</span></span><br><span class="line">foo.awesome();</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h3 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h3><ul>
<li>内部函数可以访问外部函数的作用域，如果将内部函数暴露给外部变量时，或者说内部函数在定义的词法作用域之外执行时，就产生了闭包。</li>
<li>闭包是个非常强大的工具，可以用来实现模块模式。</li>
<li>模块的特征：<ul>
<li>为创建内部作用域而调用一个包装函数；</li>
<li>包装函数的返回值必须至少包含一个对内部函数的引用，这样就会创建涵盖整个包装函数内部作用域的闭包；</li>
</ul>
</li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>William Leung
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E05/" title="《你不知道的JavaScript(上)》S01E05">https://gitee.com/lianghuilin/murmur.git/reading_notes/《你不知道的JavaScript-上-》S01E05/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/murmur/tags/%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript/" rel="tag"># 你不知道的JavaScript</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/murmur/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E04/" rel="prev" title="《你不知道的JavaScript(上)》S01E04">
                  <i class="fa fa-chevron-left"></i> 《你不知道的JavaScript(上)》S01E04
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/murmur/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS02E01/" rel="next" title="《你不知道的JavaScript(上)》S02E01">
                  《你不知道的JavaScript(上)》S02E01 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






      

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">
      

      

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">William Leung</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
    <span title="站点总字数">142k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">2:09</span>
  </span>
</div>
<div class="busuanzi-count">
    <span id="busuanzi_container_site_uv">
      本站访客数<span id="busuanzi_value_site_uv"></span>人次
    </span>
    <span id="busuanzi_container_site_pv">
        本站总访问量<span id="busuanzi_value_site_pv"></span>次
    </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/murmur/js/utils.js"></script><script src="/murmur/js/motion.js"></script><script src="/murmur/js/next-boot.js"></script>

  
















  <script>
    NProgress.configure({
      showSpinner: true
    });
    NProgress.start();
    document.addEventListener('readystatechange', () => {
      if (document.readyState === 'interactive') {
        NProgress.inc(0.8);
      }
      if (document.readyState === 'complete') {
        NProgress.done();
      }
    });
    document.addEventListener('pjax:send', () => {
      NProgress.start();
    });
    document.addEventListener('pjax:success', () => {
      NProgress.done();
    });
  </script>


  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>








  

  

</body>
</html>
